/**
 * Copyright (C) 2007 The AsyncMail Group <asyncmail@googlegroups.com>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *         http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.asyncmail.common;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;

public class MailAddress {
    private InternetAddress address;

    private String domainPart;

    private String localPart;

    public MailAddress(String rawAddress) throws AddressException {
        address = new InternetAddress(rawAddress, true);
        String[] args = splitAddress(address.getAddress());
        localPart = args[0];
        domainPart = args[1];
    }

    /**
     * Return the localpart of the given emailaddress
     * 
     * @param address
     *                the emailaddress
     * @return localpart
     */
    public String getLocalPart() {
        return localPart;
    }

    /**
     * Return the domainpart of the given emailaddress
     * 
     * @param address
     *                the emailaddress
     * @return domainpart
     */
    public String getDomainPart() {
        return domainPart;
    }

    /**
     * Return the generated InternetAddress
     * 
     * @return address
     */
    public InternetAddress getInternetAddress() {
        return address;
    }

    private String[] splitAddress(String rawAddress) throws AddressException {
        String[] parts = rawAddress.split("@", 2);

        if (parts.length < 2) {
            throw new AddressException("No domain present");
        } else {
            return parts;
        }

    }

    /**
     * Return MailAddress as String
     * 
     * @return mailAddress
     */
    public String getAddressAsString() {
        return address.getAddress();
    }

    /**
     * @see java.lang.Object#toString()
     */
    public String toString() {
        return getAddressAsString();
    }

}
